package com.jzg.jcptadmin.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.adpter.TaskViewStadusAdapter;
import com.jzg.jcptadmin.app.AppManager;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.StatusData;
import com.jzg.jcptadmin.data.vo.SuccessData;
import com.jzg.jcptadmin.data.vo.TaskViewData;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.presenter.TaskViewPresenter;
import com.jzg.jcptadmin.viewinterface.TaskViewInterface;
import com.orhanobut.logger.Logger;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.pedant.SweetAlert.SweetAlertDialog;

import static com.jzg.jcptadmin.R.id.et_content;

/**
 * Created by jzg on 2015/12/24.
 * 专业线下详情
 */
public class TaskViewActivity extends BaseActivity implements View.OnTouchListener, View.OnClickListener, TaskViewInterface {

    @Bind(R.id.tv_right)
    TextView tvOperation;//操作
    @Bind(R.id.title_content)
    TextView titleContent;
    /*---------------------*/

    private LinearLayoutManager mLayoutManager;
    private PopupWindow pwMyPopWindow;
    private ListView lvPopupList;
    private ArrayList<Map<String, String>> moreList;
    // private int NUM_OF_VISIBLE_LIST_ROWS = 3;// 指定popupwindow中Item的数量

    private TextView tv_pinggujieguo;
    private TextView tv_guzhijieguo;
    private List<StatusData.ItemListEntity.FastOffLineBtnEntity.ItemEntity> staduslist;
    private TaskViewStadusAdapter taskViewStadusAdapter;
    private TaskViewPresenter taskViewPresenter;
    private String id;
    private TaskViewData datas;
    private ArrayList<String> statusList1 = new ArrayList<>();
    private LinearLayout ll_pinggu;
    private String price1;
    private StatusData statusData;
    private TextView tv_mvin;
    private TextView tv_mlianxiren;
    private TextView tv_mphone;
    private TextView brand_content;
    private TextView card_date_content;
    private TextView mileage_content;
    private TextView area_content;
    private TextView tv_mchengjiaojia;
    private RelativeLayout rl_lianxiren;
    private RelativeLayout rl_lianxidianhua;
    //private TextView tv_mbeizhu;
    private User user;
    private TextView tv_des;
    private LinearLayout llC2b;
    private LinearLayout llB2c;
    private LinearLayout llPinggu1;
    private TextView pricePingguc2b;
    private TextView pricePinggub2c;
    private String titleStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_view);
        user = appContext.getUser();
        id = getIntent().getStringExtra(Constant.ACTIVITY_OFFINEID);
        titleStr = getIntent().getStringExtra("title");
        ButterKnife.bind(this);
        titleContent.setText("任务查看");
        tvOperation.setText("操作");
        taskViewPresenter = new TaskViewPresenter(DataManager.getInstance());
        taskViewPresenter.attachView(this);
        if (id != null) {
            showDialog();
            taskViewPresenter.loadTaskView(id, appContext.getUser().getUserId() + "");
        }
        statusData = appContext.getStatus();
        initview();
    }

    private void initdata(TaskViewData data) {
//        //产品类型
//        if (!TextUtils.isEmpty(data.getProduct_type())) {
//            product_type.setVisibility(View.VISIBLE);
//            product_type.setText(data.getProduct_type());
//        } else {
//            product_type.setVisibility(View.GONE);
//        }
        tv_mvin.setText(data.getVin());
        if (user.getIsShowContact().equals("0")) {
            //易鑫登陆不显示联系人和联系电话
        } else {
            tv_mlianxiren.setText(data.getLikeMan());
            tv_mphone.setText(data.getLikeTel());
        }
        //tv_mbeizhu.setText(data.getDes());
        if (TextUtils.isEmpty(data.getBusinessPrice())) {
//            tv_mchengjiaojia.setText("");
        } else {
           /* try {
                String str = data.getBusinessPrice();
                BigDecimal bd = new BigDecimal(Double.parseDouble(str));
                tv_mchengjiaojia.setText(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "万元");//成交价
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            if (!data.getBusinessPrice().equals("0")) {
                tv_mchengjiaojia.setText(data.getBusinessPrice() + "元");
            }

        }
        brand_content.setText(data.getFullName());
        if (TextUtils.isEmpty(data.getRegDateYear()) || TextUtils.isEmpty(data.getRegDateMonth()) || data.getRegDateYear().equals("1")) {
//            card_date_content.setText(data.getRegDateYear() +""+ data.getRegDateMonth());
        } else {
            card_date_content.setText(data.getRegDateYear() + "-" + data.getRegDateMonth());
        }
        if (!TextUtils.isEmpty(data.getMileage())) {
            mileage_content.setText(data.getMileage() + " 公里");
        }
        if (data.getProvName().equals(data.getCityName())) {
            area_content.setText(data.getProvName());
        } else {
            area_content.setText(data.getProvName() + " " + data.getCityName());
        }
//        if (data.getIsShowPrice().equals("1")) {
//            ll_pinggu.setVisibility(View.VISIBLE);
//            tv_pinggujieguo.setText(data.getApprasieDes());
////            String[] price = data.getApprasiePrice().split("\\.");
////            if(price.length>1){
////                if(price[1].length()>2){g(0, data.getApprasiePrice().length()-2);
////                    tv_guzhijieguo.setText(price1 + "万元");
////                }else{
////                    price1 =  data.getApprasiePrice().substrin
////                    tv_guzhijieguo.setText(data.getApprasiePrice() + "万元");
////                }
////            }else{
////                tv_guzhijieguo.setText(data.getApprasiePrice() + "万元");
////            }
//            try {
//                String str = data.getApprasiePrice();
//                BigDecimal bd = new BigDecimal(Double.parseDouble(str));
//                tv_guzhijieguo.setText(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "万元");
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        } else {
//            ll_pinggu.setVisibility(View.GONE);
//
//        }

        if (data.getIsShowPrice().equals("0")) {
            ll_pinggu.setVisibility(View.GONE);
        } else {
//            String[] price = details.getAppraise().split("\\.");
//            if (price.length > 1) {
//                if (price[1].length() > 2) {
//                    String price1 = details.getAppraise().substring(0, details.getAppraise().length() - 2);
//                    pricePinggu.setText(price1 + "万元");
//                } else {
//                    pricePinggu.setText(details.getAppraise() + "万元");
//                }
//            } else {
//                pricePinggu.setText(details.getAppraise() + "万元");
//            }
            try {
                ll_pinggu.setVisibility(View.VISIBLE);
                tv_pinggujieguo.setText(data.getApprasieDes());
                if (user.getIsDL().equals("1")) {//1是第三方机构  显示一个价格
                    llPinggu1.setVisibility(View.VISIBLE);
                    llB2c.setVisibility(View.GONE);
                    llC2b.setVisibility(View.GONE);
                    String str = data.getApprasiePrice();
                    BigDecimal bd = new BigDecimal(Double.parseDouble(str));
                    tv_guzhijieguo.setText(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "万元");
                } else {//显示两个价格
                    String strB2C = data.getSalePriceB2C();//车商售车价
                    String strC2B = data.getSalePriceC2B();//车商收车价
                    BigDecimal bdB2C = new BigDecimal(Double.parseDouble(strB2C));
                    BigDecimal bdC2B = new BigDecimal(Double.parseDouble(strC2B));
                    llPinggu1.setVisibility(View.GONE);
                    llB2c.setVisibility(View.VISIBLE);
                    llC2b.setVisibility(View.VISIBLE);
                    DecimalFormat fnum = new DecimalFormat("##0.00");
                    pricePinggub2c.setText(fnum.format(bdB2C) + "万元");
                    pricePingguc2b.setText(fnum.format(bdC2B) + "万元");
                }
                /*String str = details.getAppraise();
                BigDecimal bd = new BigDecimal(Double.parseDouble(str));
                pricePinggu.setText(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "万元");*/
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        tv_des.setText(data.getDes());
    }

    private void initview() {
        //产品类型
        tv_mvin = (TextView) findViewById(R.id.tv_mvin);
        tv_mlianxiren = (TextView) findViewById(R.id.tv_mlianxiren);
        tv_mphone = (TextView) findViewById(R.id.tv_mphone);
        brand_content = (TextView) findViewById(R.id.brand_content);
        card_date_content = (TextView) findViewById(R.id.card_date_content);
        mileage_content = (TextView) findViewById(R.id.mileage_content);
        area_content = (TextView) findViewById(R.id.area_content);
        //tv_mbeizhu = (TextView) findViewById(R.id.tv_mbeizhu);
        tv_pinggujieguo = (TextView) findViewById(R.id.tv_pinggujieguo);
        tv_guzhijieguo = (TextView) findViewById(R.id.tv_guzhijieguo);
        ll_pinggu = (LinearLayout) findViewById(R.id.ll_pinggu);
        tv_mchengjiaojia = (TextView) findViewById(R.id.tv_mchengjiaojia);
        rl_lianxiren = (RelativeLayout) findViewById(R.id.rl_lianxiren);
        rl_lianxidianhua = (RelativeLayout) findViewById(R.id.rl_lianxidianhua);
        llC2b = (LinearLayout) findViewById(R.id.ll_c2b);
        llB2c = (LinearLayout) findViewById(R.id.ll_b2c);
        llPinggu1 = (LinearLayout) findViewById(R.id.ll_pinggu1);
        pricePingguc2b = (TextView) findViewById(R.id.price_pingguc2b);
        pricePinggub2c = (TextView) findViewById(R.id.price_pinggub2c);
        tv_des = (TextView) findViewById(R.id.tv_des);
        View view1 = findViewById(R.id.view1);
        View view2 = findViewById(R.id.view2);
        tvOperation.setOnClickListener(this);
        if (user.getIsShowContact().equals("0")) {
            //易鑫登陆不显示联系人和联系电话
            rl_lianxiren.setVisibility(View.GONE);
            rl_lianxidianhua.setVisibility(View.GONE);
            view1.setVisibility(View.GONE);
            view2.setVisibility(View.GONE);
        } else {
            rl_lianxiren.setVisibility(View.VISIBLE);
            rl_lianxidianhua.setVisibility(View.VISIBLE);
            view1.setVisibility(View.VISIBLE);
            view2.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 发送回复的内容
     * //
     */
//    public void sendContent() {
//        String contnet = et_content
//                .getText().toString().trim();
//        if (TextUtils.isEmpty(contnet)) {
//            Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        CommentData data = new CommentData();
//        data.setUsername("评估师1");
//        data.setContnet(contnet);
//        data.setTime(StandardDate.getStandardDate(System.currentTimeMillis() + ""));
//        list.add(data);
//        adapter.updatalist(list);
//        adapter.notifyDataSetChanged();
//        et_content.setText("");
//    }
    public void onOperation(View view) {

    }

    //解决EditText在ListView中不能滚动
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case et_content:
                v.getParent().requestDisallowInterceptTouchEvent(true);
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        v.getParent().requestDisallowInterceptTouchEvent(false);
                        break;
                }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case tv_huifu:
//                sendContent();
//                break;
            case R.id.tv_right://操作
                if (statusList1.size() > 0) {
                    if (pwMyPopWindow.isShowing()) {

                        pwMyPopWindow.dismiss();// 关闭
                    } else {

                        pwMyPopWindow.showAsDropDown(tvOperation);// 显示
                    }
                }
                break;
            default:
                break;
        }
    }

    private void iniPopupWindow() {
        LayoutInflater inflater = (LayoutInflater) this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.task_detail_popupwindow, null);
        lvPopupList = (ListView) layout.findViewById(R.id.lv_popup_list);
        pwMyPopWindow = new PopupWindow(layout);
        pwMyPopWindow.setFocusable(true);// 加上这个popupwindow中的ListView才可以接收点击事件
        if (taskViewStadusAdapter == null) {
            taskViewStadusAdapter = new TaskViewStadusAdapter(appContext, statusList1);
        }
        lvPopupList.setAdapter(taskViewStadusAdapter);
        lvPopupList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //点击操作回调,筛选操作的功能
                ScreenOperation(statusList1.get(position));
                if (pwMyPopWindow.isShowing()) {
                    pwMyPopWindow.dismiss();// 关闭
                } else {
                    pwMyPopWindow.showAsDropDown(tvOperation);// 显示
                }
            }
        });
        // 控制popupwindow的宽度和高度自适应
        lvPopupList.measure(View.MeasureSpec.UNSPECIFIED,
                View.MeasureSpec.UNSPECIFIED);
        pwMyPopWindow.setWidth(lvPopupList.getMeasuredWidth());
        /*pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 20)
                * NUM_OF_VISIBLE_LIST_ROWS);*/
       /* pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 50)
                * statusList1.size());*/
        pwMyPopWindow.setHeight((lvPopupList.getMeasuredHeight() + 20)
                * (statusList1.size() + 1));
        // 控制popupwindow点击屏幕其他地方消失
        pwMyPopWindow.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.bg_tanchu));// 设置背景图片，不能在布局中设置，要通过代码来设置
        pwMyPopWindow.setOutsideTouchable(true);// 触摸popupwindow外部，popupwindow消失。这个要求你的popupwindow要有背景图片才可以成功，如上
    }

    public void ScreenOperation(String string) {
        switch (string) {
            case "修改":
//                Intent intent = new Intent(TaskViewActivity.this, PublishTaskActivity.class);
//                intent.putExtra(Constant.ACTIVITY_INSERTID, id + "");
//                intent.putExtra(Constant.ACTIVITY_TASKVIEWDATA, datas);
//                startActivity(intent);
//                finish();
                break;
            case "删除":
                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("提示")
                        .setContentText("您确定要删除这条数据吗？")
                        .setConfirmText("是的").setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                taskViewPresenter.ZyOperationData(appContext.getUser().getUserId() + "", "DelInfo", id, "", "");
                                sDialog.dismissWithAnimation();
                            }
                        }).show();
                break;
            case "退回":

                Intent intent4 = new Intent(this, RejectActivity.class);
                intent4.putExtra("id", id);
                intent4.putExtra("status", "专业线下退回");
                startActivity(intent4);
                AppManager.getAppManager().finishActivity(OfflineDetectionActivity.class);
                break;
            case "恢复":
                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("提示")
                        .setContentText("您确定要恢复这条数据吗？")
                        .setConfirmText("是").setCancelText("否")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {

                                taskViewPresenter.ZyOperationData(appContext.getUser().getUserId() + "", "HuiFu", id, "", "");
                                sDialog.dismissWithAnimation();
                            }
                        }).show();
                break;
            case "审核":
                Intent intent1 = new Intent(TaskViewActivity.this, ExamineActivity.class);
                intent1.putExtra("id", id);
                intent1.putExtra("type", "ShenHe");
                startActivity(intent1);
                break;

            default:

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    public void showError(String error) {
        dismissDialog();
        Toast.makeText(appContext, Constant.errr_net, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showViewDatas(TaskViewData datas) {
        if (datas.getStatus().equals("100")) {
            dismissDialog();
            this.datas = datas;
            //初始化操作的数据
            if (statusData != null) {
                initOperationData();
            } else {
                Toast.makeText(TaskViewActivity.this, "无操作数据", Toast.LENGTH_SHORT).show();
            }
            initdata(datas);
            Logger.e("返回详情数据" + datas.toString());
        } else {
            Toast.makeText(TaskViewActivity.this, datas.getStatus() + "加载失败", Toast.LENGTH_SHORT).show();
        }
    }

    //初始化操作的数据
    private void initOperationData() {
        staduslist = statusData.getItemList().getFastOffLineBtn().getItem();
        String[] str1 = datas.getButtonstr().split(",");
        Logger.e("线下操作数据" + datas.getButtonstr());
        for (int i = 0; i < staduslist.size(); i++) {
            for (int j = 0; j < str1.length; j++) {
                if (staduslist.get(i).getId().equals(str1[j])) {
                    statusList1.add(staduslist.get(i).getValue());
                }
            }
        }
        if (statusList1.size() <= 0) {
            tvOperation.setVisibility(View.GONE);
        } else {
            tvOperation.setVisibility(View.VISIBLE);
        }
        iniPopupWindow();
    }

    @Override
    public void OperationDatas(SuccessData datas) {
        dismissDialog();
        if (datas.getStatus() == 100) {
            AppManager.getAppManager().finishActivity(OfflineDetectionActivity.class);
            dismissDialog();
            Intent intent = new Intent(TaskViewActivity.this, OfflineDetectionActivity.class);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(TaskViewActivity.this, datas.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }
}
